package com.polytech.diploma.SQLGenerator.Oracle.DBEntityGenerators;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.polytech.diploma.DBTablesHelper.DBEntities.CHTable;
import com.polytech.diploma.DBTablesHelper.DBEntities.CTTrigger;
import com.polytech.diploma.SQLGenerator.Oracle.Statements.Table;

public class ChangeTableTriggerGenerator {
	
	private static long serialVersionUID = 1L;
	private transient static ChangeTableTriggerGenerator ctTriggerGenerator = null;
	
	public static ChangeTableTriggerGenerator getInstance()
	{
		if (ctTriggerGenerator == null)
			ctTriggerGenerator = new ChangeTableTriggerGenerator();
		return ctTriggerGenerator;
	}
	
	public List<CTTrigger> generateTrigger(Table mp, CHTable changeTable)
	{
		List<CTTrigger> triggerList = new ArrayList<CTTrigger>();
		
		Map<String, List<String>> fieldMap = new HashMap<String, List<String>>();
		
		fieldMap = mp.getTablesWithFields(fieldMap);
		
		for(String tableName : fieldMap.keySet())
		{
			CTTrigger trigger = new CTTrigger();
			String result = new String();
			String insertStr = new String();
			String deleteStr = new String();
			String updateStr = new String();
			List<String> fieldList = fieldMap.get(tableName);
			boolean first = true;
			
			if(fieldList != null)
				for(String field : fieldList)
				{
					if(first)
					{
						result += " OF " + field;
						first = false;
						continue;
					}					
					result += ", " + field;
				}
			
			trigger.setTrigger("TRIG_CT_"+tableName+"_"+serialVersionUID);
			result += "CREATE OR REPLACE TRIGGER " + trigger.getTrigger() + "\r\n" +
							"AFTER INSERT OR UPDATE OR DELETE " + result + " ON " + changeTable.getChTable() + "\r\n" +
							"FOR EACH ROW\r\n" +
							"BEGIN\r\n";
			
			serialVersionUID++;
			
			insertStr = "IF INSERTING THEN\r\n" +
					"INSERT INTO " + changeTable.getChTable() + " VALUES (\r\n";
			deleteStr = "ELSIF DELETING THEN\r\n" +
					"INSERT INTO " + changeTable.getChTable() + " VALUES (\r\n";
			updateStr = "ELSIF UPDATING THEN\r\n" +
					"INSERT INTO " + changeTable.getChTable() + " VALUES (\r\n";
			
			if(fieldList != null)
			{
				for(String field : fieldList)
				{
					insertStr += ":NEW." + field + "_NEW ";
					deleteStr += "NULL";
					updateStr += ":NEW." + field + "_NEW ";
					
					insertStr += ", NULL, ";
					deleteStr += ", :OLD." + field + "_OLD, ";
					updateStr += ", :OLD." + field + "_OLD, ";
				}
			}			
			
			insertStr += "'I');\r\n";
			deleteStr += "'D');\r\n";
			updateStr += "'U');\r\n";
			
			result += insertStr + deleteStr + updateStr;
			result += "END IF;\r\n" +
						"END;\r\n";
			
			trigger.setCreateTrigScript(result);
			trigger.setDropTrigScript("DROP TRIGGER "+ trigger.getTrigger() + ";\r\n");
			triggerList.add(trigger);
		}	
		return triggerList;
	}
	
}
